package com.jd.basic.util;

import com.jd.basic.jwt.JwtUtils;
import com.jd.basic.jwt.LoginData;
import com.jd.basic.jwt.Payload;
import com.jd.basic.jwt.RsaUtils;
import com.jd.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 获取当前登陆人信息
 */
public class LoginContext {
    public static Logininfo getLoginfo(HttpServletRequest request) {
        // 获取加密后的jwtToken
        String token = request.getHeader("token");
        if (token != null) {
            try {
                // 获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                // 解密
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                // 获取登录信息
                Logininfo logininfo = payload.getLoginData().getLogininfo();
                return logininfo;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
